package com.yl.immodule.fragment.model;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.camera.base.Log.YLogImpl;
import com.camera.base.util.YLIMConfig;
import com.camera.base.v.models.BaseViewModel;
import com.camera.routemodule.RouterPath;
import com.unionbroad.greendao.Channel;
import com.unionbroad.app.eventbus.ChannelChangedEvent;
import com.yl.immodule.bean.YChannel;
import com.yl.immodule.func.AddChannelFunc;
import com.yl.immodule.util.MeetManger;
import com.yl.immodule.v.AvActivity;

import java.util.ArrayList;
import java.util.List;

public class ChannelListViewModel extends BaseViewModel {
    private final String TAG = ChannelListViewModel.class.getSimpleName();
    
    // 使用backing property模式
    private final MutableLiveData<List<YChannel>> _channels = new MutableLiveData<>(new ArrayList<>());
    public LiveData<List<YChannel>> channels = _channels;
    
    private final MutableLiveData<Boolean> _isLoading = new MutableLiveData<>(false);
    public LiveData<Boolean> isLoading = _isLoading;

    
    private final MutableLiveData<YChannel> _currentChannel = new MutableLiveData<>();
    public LiveData<YChannel> currentChannel = _currentChannel;
    private final MutableLiveData<YChannel> _disconnectChannel = new MutableLiveData<>();
    public LiveData<YChannel> disconnectChannel = _disconnectChannel;
    private final MutableLiveData<Boolean> _showAddChannelDialog = new MutableLiveData<>();
    public LiveData<Boolean> showAddChannelDialog = _showAddChannelDialog;

    public ChannelListViewModel() {
        ICPRtcManager.getsInstance().addEventHandler(icpRtcEventHandler);
        loadChannels();
        ICPRtcManager.getsInstance().pttStateNotify();
        Channel currentPttChannel = ICPRtcManager.getsInstance().getCurrentPttChannel();
        if (currentPttChannel != null) {
            _currentChannel.setValue(new YChannel(currentPttChannel, false, true));
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        ICPRtcManager.getsInstance().removeEventHandler(icpRtcEventHandler);
    }

    /**
     * 刷新频道列表数据
     */
    public void refreshChannels() {
        _isLoading.setValue(true);
        loadChannels();
        _isLoading.setValue(false);
        //刷新一次onPttStateEvent    获取当前连接的频道
        ICPRtcManager.getsInstance().pttStateNotify();
    }
    
    /**
     * 从ICPRtcManager获取频道列表
     */
    private void loadChannels() {
        List<Channel> channelList = ICPRtcManager.getsInstance().getAudioPttChannelList();
        List<YChannel> yChannelList = new ArrayList<>();
        if (channelList != null) {
            for (Channel channel : channelList) {
                Log.e(TAG, "{\"foctory\":"+  channel.getChannelNumber());
                yChannelList.add(new YChannel(channel, false, false));
            }
        }
        _channels.setValue(yChannelList);
    }
    
    /**
     * 删除语音对讲群组
     */
    public void removeAudioPTTChannel(final YChannel yChannel) {
        ICPRtcManager.getsInstance().removeAudioPTTChannel(yChannel.getChannel().getChannelNumber(), 
            new ICPRtcEventHandler.Callback<Boolean>() {
                @Override
                public void onResponse(Boolean success) {
                    if (success != null && success) {
                        // 更新列表
                        List<YChannel> currentList = _channels.getValue();
                        if (currentList != null) {
                            currentList.remove(yChannel);
                            _channels.setValue(currentList);
                        }
                        getToastString().setValue("删除成功");
                    } else {
                        getToastString().setValue("删除失败");
                    }
                }
            });
    }
    
    /**
     * 加入语音对讲群组
     */
    public void joinChannel(String channelNumber) {
        ICPRtcManager.getsInstance().joinChannel(channelNumber);
    }
    
    /**
     * 启动视频会议
     */
    public void startVideoMeeting(Context context, String channelNumber) {
        if (YLIMConfig.windowManagerChoose) {
//            MeetManger.getInstance().startMeet(
//                    context.getApplicationContext(),
//                    0,
//                    channelNumber,
//                    null,
//                    ICPRtcEventHandler.SessionType.TYPE_VIDEO_MEETING,
//                    null,
//                    false);
            ARouter.getInstance()
                    .build(RouterPath.path.av_pop_activity)
                    .withString("callerId", channelNumber)
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_MEETING)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        } else {
//            Intent intent = new Intent(context.getApplicationContext(), AvActivity.class);
//            intent.putExtra("callerId", channelNumber);
//            intent.putExtra("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_MEETING);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.getApplicationContext().startActivity(intent);
            ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withString("callerId", channelNumber)
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_MEETING)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        }
    }

    /**
     * 启动语音会议
     */
    public void startAudioMeeting(Context context, String channelNumber) {
        if (YLIMConfig.windowManagerChoose) {
//            MeetManger.getInstance().startMeet(
//                    context.getApplicationContext(),
//                    0,
//                    channelNumber,
//                    null,
//                    ICPRtcEventHandler.SessionType.TYPE_AUDIO_MEETING,
//                    null,
//                    false);
            ARouter.getInstance()
                    .build(RouterPath.path.av_pop_activity)
                    .withString("callerId", channelNumber)
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_MEETING)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        } else {
//            Intent intent = new Intent(context.getApplicationContext(), AvActivity.class);
//            intent.putExtra("callerId", channelNumber);
//            intent.putExtra("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_MEETING);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.getApplicationContext().startActivity(intent);

            ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withString("callerId", channelNumber)
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_MEETING)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        }
    }

    /**
     * 启动添加群组
     */
    public void startAddChannel() {
        Log.e(TAG, "startAddChannel: ");
        _showAddChannelDialog.setValue(true);
    }

    /**
     * 处理 power 按钮点击事件
     */
    public void handlePowerClick(YChannel channel) {
        if (channel != null) {
            boolean success = ICPRtcManager.getsInstance().leaveChannel(
                channel.getChannel().getChannelNumber() + ""
            );
            if (success) {
                // 创建新的列表和对象来触发更新
                List<YChannel> currentList = new ArrayList<>(_channels.getValue());
                if (currentList != null) {
                    for (int i = 0; i < currentList.size(); i++) {
                        YChannel item = currentList.get(i);
                        if (item.getChannel().getChannelNumber().equals(
                            channel.getChannel().getChannelNumber()
                        )) {
                            YChannel newChannel = new YChannel(
                                item.getChannel(),
                                item.isListener(),
                                false  // 设置新的connect状态
                            );
                            currentList.set(i, newChannel);
                            break;
                        }
                    }
                    _channels.postValue(currentList);
                }
            }
        }
    }

    private ICPRtcEventHandler icpRtcEventHandler = new ICPRtcEventHandler() {
        @Override
        public void onPttStateEvent(long sessionId, String channelId, int state) {
            super.onPttStateEvent(sessionId, channelId, state);
            if (TextUtils.isEmpty(channelId)) {
                YLogImpl.i(TAG, "onPttStateEvent:"+channelId);
                //当前无附着频道
            } else {
                if (state == ICPRtcEventHandler.PttState.CONNECTED) {
                    //当前已经连接
                    //更新item 的状态
                    Channel currentPttChannel = ICPRtcManager.getsInstance().getCurrentPttChannel();
                    if (currentPttChannel != null) {
                        _currentChannel.postValue(new YChannel(currentPttChannel, false, true));
                    }
                } else if (state == ICPRtcEventHandler.PttState.CONNECTING) {
                    //频道连接中
                } else {
                    //频道未连接
                    //通过channelId  和 _channels 里面的 channelNumber 进行匹配   修改YChannel的isConnect为false
                    List<YChannel> currentList = new ArrayList<>(_channels.getValue());
                    if (currentList != null) {
                        for (int i = 0; i < currentList.size(); i++) {
                            YChannel yChannel = currentList.get(i);
                            if (yChannel.getChannel().getChannelNumber().toString().equals(channelId)) {
                                // 创建新的YChannel对象
                                YChannel newChannel = new YChannel(
                                    yChannel.getChannel(),
                                    yChannel.isListener(),
                                    false  // 设置新的connect状态
                                );
                                currentList.set(i, newChannel);
                                break;
                            }
                        }
                        _channels.postValue(currentList);
                    }
                }
            }
        }
        @Override
        public void onChannelChangedEvent(ChannelChangedEvent event) {
            YLogImpl.i(TAG, "onChannelChangedEvent: action "+event.action);
            switch (event.action) {
                case ChannelChangedEvent.ACTION_ADD_GROUP:
                    //BUG  暂时先刷新一遍
                    refreshChannels();

//                    if (event.channel != null){
//                        List<YChannel> channels = _channels.getValue();
//                        channels.add(new YChannel(event.channel, false, false));
//                        _channels.postValue(channels);
//                    }
                    break;
                case ChannelChangedEvent.ACTION_DEL_GROUP:

                    break;
                case ChannelChangedEvent.ACTION_DEL_USER:

                    break;
                case ChannelChangedEvent.ACTION_ADD_USER:

                    break;
                case ChannelChangedEvent.ACTION_EDIT_USER:

                    break;
                case ChannelChangedEvent.ACTION_SWITCH:

                    break;
            }

        }
    };
} 